<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('user_roles', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id')->comment('用户ID');
            $table->unsignedBigInteger('role_id')->comment('角色ID');
            $table->date('start_date')->comment('开始日期');
            $table->date('end_date')->nullable()->comment('结束日期');
            $table->enum('status', ['active', 'inactive'])->default('active')->comment('状态');
            $table->unsignedBigInteger('assigned_by')->nullable()->comment('分配人ID');
            $table->timestamp('assigned_at')->nullable()->comment('分配时间');
            $table->text('reason')->nullable()->comment('分配原因');
            $table->timestamps();
            
            // 外键约束
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->foreign('assigned_by')->references('id')->on('users')->onDelete('set null');
            
            // 索引
            $table->index(['user_id', 'status']);
            $table->index(['role_id', 'status']);
            $table->index(['start_date', 'end_date']);
            
            // 唯一约束：同一用户在同一时间段只能有一个相同角色
            $table->unique(['user_id', 'role_id', 'start_date'], 'unique_user_role_start_date');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('user_roles');
    }
};
